package la.bbs558.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import la.bbs558.dao.InvitationCodeDao;
import la.bbs558.entity.InvitationCode;
import la.bbs558.entity.UserData;
import la.bbs558.entity.vo.InvitationCodeVO;
import la.bbs558.service.InvitationCodeService;
import la.bbs558.service.UserDataService;
import la.bbs558.util.Objs;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Optional;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: Shanks
 * @date: 2023/12/15 17:01
 * @desc:
 */
@Service
@RequiredArgsConstructor
public class InvitationCodeServiceImpl extends ServiceImpl<InvitationCodeDao, InvitationCode> implements InvitationCodeService {

    private final InvitationCodeDao invitationCodeDao;

    private final UserDataService userDataService;

    private final Lock inviteCodeLock = new ReentrantLock();

    //创建邀请码
    @Override
    public String getInviteCode(){
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<UserData> userData = userDataService.lambdaQuery()
                .select(UserData::getInvitationCode, UserData::getUserId)
                .eq(UserData::getUserId, userId)
                .oneOpt();
        Objs.isTrue(userData.isPresent(), "用户不存在");
        String invitationCode = userData.get().getInvitationCode();
        Objs.isTrue(invitationCode != null, "邀请码生成错误，请联系管理员");
        return invitationCode;
    }

    @Override
    public void getInvitationList(Page<InvitationCodeVO> page) {
        invitationCodeDao.selectInvitationList(page, StpUtil.getLoginIdAsLong());
    }
}
